<template>
  <div class="app-container">
    <el-dialog :title="id ? '修改' : '新增'" :visible.sync="visible" width="800px" :before-close="handleClose"
      append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="建筑编号" prop="buildingNo">
          <el-input v-model="form.buildingNo" :disabled="id ? true : false" />
        </el-form-item>
        <el-form-item label="建筑名称" prop="buildingName">
          <el-input v-model="form.buildingName" />
        </el-form-item>
        <el-form-item label="建筑图片" prop="file">
          <FileUpload v-model="form.file" :fileType="['png', 'jpg', 'jpeg']" :url="url" @input="getFirelist"
            @deleteFile="deleteFile" @giveMediaType="giveMediaType" ref="fileUpload" :dynamicHeaders="dynamicHeaders"
            :dynamicMethod="dynamicMethod" :dynamicUrl="dynamicUrl" :ossId="ossId" :limit="3" :drag="true"
            :listType="'picture'"></FileUpload>
        </el-form-item>
        <el-form-item label="建筑描述" prop="description">
          <editorCom ref="editorCom" :value="form.description" @input="handleInput"></editorCom>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload";
import editorCom from "@/components/Editor";
import { postOssUpload } from "@/api/oss";
import { addBuilding, editBuilding } from "@/api/map";
export default {
  name: "Add",
  components: {
    FileUpload,
    editorCom,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    objTarget: {
      type: String,
      default: "",
    },
  },
  data() {
    // 定义校验规则
    const validateBuildingNo = (rule, value, callback) => {
      if (!value) {
        callback(new Error("建筑编号不能为空"));
      } else if (!/^[0-9]+$/.test(value)) {
        callback(new Error("建筑编号只能为数字"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      uploadParams: {
        path: "map-building",
        name: "建筑图片",
        permission: "tenant",
        suffix: "",
        mediaType: "",
        sizeLimit: "",
        attachment: "",
      },
      rules: {
        buildingNo: [
          { required: true, validator: validateBuildingNo, trigger: "blur" },
        ],
        buildingName: [
          { required: true, message: "建筑名称不能为空", trigger: "blur" },
        ],
        file: [],
        description: [],
      },
      url: "",
      ossId: "",
      dynamicHeaders: {},
      dynamicMethod: "PUT",
      dynamicUrl: null,
      imageOidList: [],
    };
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          this.giveDetail();
        }
      },
      deep: false,
      immediate: true,
    },
  },
  methods: {
    handleInput(val) {
      this.form.description = val;
    },
    giveDetail() {
      let objTarget = JSON.parse(this.objTarget);
      // console.log(objTarget);
      this.form = {
        buildingNo: objTarget.buildingNo,
        buildingName: objTarget.buildingName,
        description: objTarget.description,
        file: objTarget.imageUrlList,
      };
      this.imageOidList = objTarget.imageOidList;
    },
    giveMediaType(mediaType) {
      this.uploadParams.mediaType = mediaType;
      this.uploadParams.suffix = this.uploadParams.mediaType.match(/\/(.+)/)[1]
      this.requestpostOssUpload();
    },
    requestpostOssUpload() {
      postOssUpload(this.uploadParams)
        .then((res) => {
          if (res.success) {
            this.dynamicHeaders = res.data.headers || {};
            this.dynamicMethod = res.data.method || "PUT";
            this.dynamicUrl = res.data.uploadUrl || "";
            this.ossId = res?.data?.ossId ?? null;
            // 触发子组件上传
            // console.log(this.$refs.fileUpload.$refs.upload, "1111111");
            // this.$refs.fileUpload.$refs.upload.submit();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getFirelist(data) {
      data.forEach((item) => {
        // imageOidList不包含该ossId则push
        if (item.ossId && !this.imageOidList.includes(item.ossId)) {
          this.imageOidList.push(item.ossId);
        }
      });
      this.dynamicHeaders = {};
      this.dynamicMethod = "PUT";
      this.dynamicUrl = null;
      this.ossId = "";
      console.log(this.imageOidList, "imageOidList");
    },
    deleteFile(file) {
      // 找到form.file中对应的对象，删除
      let index = this.form.file.findIndex((item) => {
        if (typeof item === "object" && Object.keys(item).length > 0) {
          return item.url === file.url;
        } else {
          return item === file.url;
        }
      });
      if (index !== -1) {
        // 找到imageOidList中对应的对象，删除
        this.form.file.splice(index, 1);
        this.imageOidList.splice(index, 1);
      }
      console.log(this.form);
      console.log(this.imageOidList);
    },
    cancle() {
      this.handleClose(false);
    },
    sub() {
      // 触发表单校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验通过，执行提交逻辑
          let requestWay, msg, errmsg;
          let queryParams = {
            buildingNo: this.form.buildingNo,
            buildingName: this.form.buildingName,
            description: this.form.description,
            imageOidList: this.imageOidList,
          };
          if (this.id) {
            requestWay = editBuilding;
            queryParams.buildingId = this.id;
            msg = "修改成功";
            errmsg = "修改失败";
          } else {
            requestWay = addBuilding;
            msg = "新增成功";
            errmsg = "新增失败";
          }
          console.log("提交表单数据:", queryParams);
          requestWay(queryParams)
            .then((res) => {
              if (res.success) {
                this.$message.success(msg);
                this.handleClose(true);
              } else {
                this.$message.error(errmsg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("表单校验未通过");
          return false;
        }
      });
    },
    handleClose(status) {
      this.form = {};
      this.imageOidList = [];
      // 重置表单
      this.$refs.form.resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style lang="scss" scoped></style>
